package Share;

import java.io.*;
import java.security.MessageDigest;
import java.util.*;

public class Certificate {
	public String owner;
	public String signer;
	public Date expiration;
	public byte[] key;
	public byte[] signature;
	
	public void serialize(DataOutputStream out) throws IOException
	{
		Util.write(out, owner);
		Util.write(out, signer);
		out.writeLong(expiration.getTime());
		Util.write(out, key);
		Util.write(out, signature);
	}
	
	
	public Certificate(String owner, String signer, Date expiration, byte[] key)
	{
		this.owner = owner;
		this.signer = signer;
		this.expiration = expiration;
		this.key = key;
	}
	
	public Certificate(DataInputStream in) throws IOException
	{
		owner = Util.readString(in);
		signer = Util.readString(in);
		expiration = new Date(in.readLong());
		key = Util.readByteArray(in);
		signature = Util.readByteArray(in);
	}
	
	public void digest(MessageDigest digest) throws UnsupportedEncodingException
	{
		digest.update(owner.getBytes("UTF-8"));
		digest.update(signer.getBytes("UTF-8"));
		digest.update(Long.toHexString(expiration.getTime()).getBytes("UTF-8"));
		digest.update(key);
		digest.update(signature);
	}
	
	public byte[] hashForSig()
	{
		try
		{
			MessageDigest digest = MessageDigest.getInstance("SHA-512");
			digest.update(owner.getBytes("UTF-8"));
			digest.update(signer.getBytes("UTF-8"));
			digest.digest(Long.toHexString(expiration.getTime()).getBytes("UTF-8"));
			digest.update(key);
			return digest.digest();
		}
		catch (Exception error)
		{
			return null;
		}
	}
}
